<?php
namespace MyAdmin\Controller;

use Think\Controller;

class OrdersController extends CommonController
{

  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model=M("Orders");
    //查询
    $tran_no = trim(I("tran_no"));
    $shop_name = trim(I("shop_name"));

    $beg_time = trim(I("beg_time"));//下单时间
    $end_time = trim(I("end_time"));

    $status = trim(I("status"));
    $flag = trim(I("flag"));
    
    $where = "u.app_id={$this->app_id} ";
    if ($tran_no) {//订单号
      $where .= " and o.tran_no like '%".trim($tran_no)."%'";
      $where_ar['tran_no']=$tran_no;
      $this->assign("tran_no", $tran_no);
    }
    if ($shop_name) {//订单号
      $where .= " and s.name like '%".trim($shop_name)."%'";
      $where_ar['shop_name']=$shop_name;
      $this->assign("shop_name", $shop_name);
    }
    if ($beg_time) {//下单时间
      $beg_time_where = strtotime($beg_time);
      $where .= " and o.created_at>='".trim($beg_time_where)."'";
      $where_ar['beg_time']=$beg_time;
      $this->assign("beg_time", $beg_time);
    }
    if ($end_time) {//下单时间
      $end_time_where = strtotime($end_time);
      $where .= " and o.created_at<'".trim($end_time_where)."'";
      $where_ar['end_time']=$end_time;
      $this->assign("end_time", $end_time);
    }
    if ($status) {//下单时间
      $where .= " and o.status = '".trim($status)."'";
      $where_ar['status']=$status;
      $this->assign("status", $status);
    }
    $order = "o.id desc";

    if($flag){
      $field = "o.*,s.name as shop_name,u.nickname as user_name,c.product_name,c.product_num,c.product_price,c.product_spec,c.spec_id";
           $list = $model->alias("o")->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
      ->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->join("left join ".C("DB_PREFIX")."order_children c on o.id=c.order_id")
      ->field($field)->where($where)->order($order)->select();

      flagOrder($list);

    }else{
        $field = "o.*,s.name as shop_name,u.nickname as user_name";

        $list = $model->alias("o")->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
        ->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")
        ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();      
    }
    foreach ($list as $key => &$value) {
      $value['created_at'] = local_time($value['created_at']);
      $value['payed_at'] = local_time($value['payed_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = '未支付';
          break;
        case 2:
          $value['status_str'] = "已支付（待发货）";
          break;
        case 3:
          $value['status_str'] = "已取消";
          break;
        case 4:
          $value['status_str'] = "已发货";
          break;
        case 5:
          $value['status_str'] = "已收货";
          break;
        case 6:
          $value['status_str'] = "申请退款";
          break;
        case 7:
          $value['status_str'] = "已完成";
          break;
        case 8:
          $value['status_str'] = "已退款";
          break;
        case 9:
          $value['status_str'] = "拒绝退款";
          break;
        case 10:
          $value['status_str'] = "同意退款";
          break;
        default:
          $value['status_str'] = "未知";
          break;
      }
    }

    $num = $model->alias("o")->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
    ->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    $this->display();
  }

  public function show()
  {
    $id = I("id", 0);
    $order = M('orders')->where("id=$id")->find();

    $field = "id,product_name,product_price,product_price,product_num,product_spec";
    $order['products'] = M("order_children")->field($field)->where("order_id=".$id)->order("id asc")->select();

    foreach ($order['products'] as $key => $value) {
      $value['product_name'] = str_replace(array("\r\n", "\r", "\n"), "", $value['product_name']);
    }

    if ($order['province']) {
      $order['address'] = $order['province']. $order['area']. $order['city']. $order['addr'];
    }

    if ($order['receiver_name']) {
      $order['picked_at'] = local_time($order['picked_at']);
    }

    $this->assign("order", $order);

    $this->display();
  }

  //改变状态
  public function change_status()
  {
    $model = M("Orders");
    $status = I("status", 2);
    $id = I("id", '');

    $post_data["status"] = $status;
    $post_data["updated_at"] = $this->now_time;
    $where = " id=".$id;
    $result = $model->where($where)->save($post_data);
    if ($result) {//$result!==false
      return_data("success", "change_status.users.success");
    } else {
      return_data("error", "change_status.users.error");
    }
  }

  //打款至商户
  public function alipay()
  {
    $id = trim(I("id"));

    $map = array(
      'o.id' => $id,
      'o.status' => 7,   //array('in','2, 4')
      'o.is_payed' => 1
      ); #判断条件
    $field = "o.*,s.alipay_name as alipay_name,s.alipay_account as alipay_account,s.rate as rate,s.app_id as app_id";
    $order = M("Orders")->alias("o")->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
    ->field($field)->where($map)->find();

    if (!$order || $order['alipay_account'] == "" || $order['alipay_name'] == "") {
      return_data("error", "alipay.order.invalid", $order);
    }
    $result = alipay_to_shop($order);

    if ($result) {
      M('messages')->where("order_id=$id and types=2 and status<2")->save(array('status' => 2));

      return_data("success", "alipay_to_shops.success");
    } else {
      return_data("error", "alipay_to_shops.error");
    }
  }

  //订单统计
  public function order_count()
  {
    $day = I("day", 7);
    $beg_time = strtotime(date("Y-m-d", $this->now_time));
    $end_time = $beg_time+24*3600;
    $where="u.app_id={$this->app_id} and o.status in (2,4,5,7,9) and o.created_at>='".$beg_time."' and o.created_at<'".$end_time."'";
    $data['num'] = M("Orders")->alias('o')->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->where($where)->count();
    $amount = M("Orders")->alias("o")->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->where($where)->sum("total_amount");
    $data['amount'] =  $amount ? $amount : '0.00';

    $a_mount_ago = $beg_time-(30-1)*24*3600;
    $orders_month = array();
    $turnover_month = array();
    for ($i = 0 ; $i < 30 ; $i++) {
      $beg_day = $a_mount_ago + $i * 24 * 3600;
      $end_day = $beg_day + 24 * 3600;
      $where="u.app_id={$this->app_id} and o.status in (2,4,5,7,9) and o.created_at>='".$beg_day."' and o.created_at<'".$end_day."'";
      $orders_month[] = M("Orders")->alias("o")->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->where($where)->count();
      $turnover_month[] = M("Orders")->alias("o")->join("left join ".C("DB_PREFIX")."users u on u.id=o.user_id")->where($where)->sum("total_amount");
    }
    $date_month = array();
    for ($i = 29 ; $i >= 0 ; $i--) {
      $date_month[]=date("m-d", strtotime('-'.$i.'day'));
    }

    $orders_week = array_slice($orders_month, 23);
    $turnover_week = array_slice($turnover_month, 23);
    $date_week = array_slice($date_month, 23);

    $data['date_week'] = json_encode($date_week);
    $data['date_month'] = json_encode($date_month);
    $data['recent_seven_days_orders'] = json_encode($orders_week);
    $data['recent_seven_days_turnover'] = json_encode($turnover_week);
    $data['recent_thirty_days_orders'] = json_encode($orders_month);
    $data['recent_thirty_days_turnover'] = json_encode($turnover_month);
    $this->assign("data", $data);
    $this->assign("day", $day);
    $this->display();
  }

  public function refund_auth()
  {
    $id = I('id', 0);

    $order = M("orders")->alias("o")
                        ->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
                        ->where("o.id=$id and (o.status=10 || o.status=6)")
                        ->field("o.*,s.app_id as app_id")
                        ->find();
    if ($order) {
      #处理退款
      $result = refund_order($order);

      if ($result['result_code'] && $result['result_code'] == 'SUCCESS') {
        M('messages')->where("order_id=$id and types=1 and status<2")->save(array('status' => 2));

        $data = array(
          'status' => 8,
          'wx_refund_id' => $result['refund_id'],
          'updated_at' => $this->now_time
        );
        M("orders")->where("id=$id")->save($data);

        return_data('success','order.refund.success');
      } else {
        return_data("error", "order.refund.fail", $result['err_code_des']);
      }
    } else {
      return_data('error','refund.order.invalid');
    }

  }

  public function finish_order()
  {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $order_id = I('id', 0);
    $app_info = $this->app_info;
    M('orders')->where("id={$order_id}")->save(array('status' => 7, 'updated_at' => $this->now_time));

    $item = M('orders')->alias('o')
             ->where("o.id={$order_id}")
             ->join("left join ".C('DB_PREFIX')."shops sp on sp.id = o.shop_id")
             ->join("left join ".C('DB_PREFIX')."apps ap on ap.id = sp.app_id")
             ->field('o.total_amount as total_amount, sp.id as shop_id, ap.id as app_id, sp.amount as shop_amount, o.id as order_id')
             ->find();
    create_amount_log($item);

    return_data('success', 'order.finish.success');
  }

  public function express_order()
  {
    $update_data = I('post.');
    $order_id = $update_data['id'];

    $update_data['status'] = 4;
    $update_data['updated_at'] = $this->now_time;
    $app_info = $this->app_info;
    $order =  M('orders')->where("id={$order_id}")->find();
    if ($app_info['receive_days'] == 0) {
      $update_data['status'] = 5;
      $update_data['picked_at'] = $this->now_time;
      if ($app_info['aftersale_days'] == 0) {
        $update_data['status'] = 7;
        //TODO: status=4 or status=2
        $item = M('orders')
                 ->where("id={$update_data['id']} and status = 2")
                 ->find();
                 // echo M('orders')->getLastSql();exit;
        $item['order_id'] = $item['id'];
        create_brokerage_log($item);
      }
    };
    $result = M('orders')->where("id={$order_id}")->save($update_data);

    if (!$result) {
      $this->error("操作失败");
    } else {
      $order_child = M('order_children')->where("order_id={$order['id']}")->find();
      $content =  "{$order_child['product_name']} 等商品";
      $order['xcx_openid'] = M('users')->where("id={$order['user_id']}")->getField('xcx_openid');
      $order['template_id'] = $app_info['express_order_template_id'];
      $order['form_id'] = $order['prepay_id'];
      $expressed_at = date('Y-m-d H:i:s', time());
      $addr = "{$order['province']} {$order['city']} {$order['area']} {$order['addr']}";
      $order['data'] = array(
        'keyword1' => array('value' => $order['tran_no'], 'color' => '#173177'),
        'keyword2' => array('value' => $content, 'color' => '#173177'),
        'keyword3' => array('value' => $addr, 'color' => '#173177'),
        'keyword4' => array('value' => $data['exp_company'], 'color' => '#173177'),
        'keyword5' => array('value' => $data['exp_no'], 'color' => '#173177'),
        'keyword6' => array('value' => $expressed_at, 'color' => '#173177')
        );
      $order['page'] = "pages/orders/order?id={$order['id']}";

      $result = send_app_msg($order, $this->app_id);

      M('messages')->where("order_id=$order_id and types=4 and status<2")->save(array('status' => 2));
      $this->success("操作成功", U("Orders/index?status={$update_data['status']}"));
    }
  }

  public function audit_refund()
  {
    $update_data = I('post.');
    $order_id = $update_data['id'];
    if ($update_data['status'] == 9 && !$update_data['refund_reject_reason']) {
      $this->error("操作失败, 请填写拒绝理由");
    }
    $app_info = $this->app_info;

    $result = M('orders')->where("id={$order_id}")->save($update_data);

    if (!$result) {
      $this->error("操作失败");
    } else {
      if ($update_data['status'] == 10) {
        $result = refund_order($order);

        if ($result['result_code'] && $result['result_code'] == 'SUCCESS') {
          M('messages')->where("order_id=$order_id and types=5 and status<2")->save(array('status' => 2));

          $update_data = array(
            'status' => 8,
            'wx_refund_id' => $result['refund_id'],
            'updated_at' => $this->now_time
          );
          M("orders")->where("id=$order_id")->save($update_data);
        }
      }
      $this->success("操作成功",  U("Orders/index?status={$update_data['status']}"));
    }
  }
}
